package com.cqs.leetcode;

/**
 * Created by cqs on 2018/4/1.
 */

public class MergeTwoSortedLists {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l2 == null) return l1;
        if (l1 == null) return l2;

        //保留头指针
        ListNode result = null;
        ListNode rc = null;
        while (l1 != null && l2 != null) {
            ListNode node;
            if (l1.val <= l2.val) {
                node = l1;
                l1 = l1.next;
            } else {
                node = l2;
                l2 = l2.next;
            }
            if (result == null) {
                result = node;
                rc = result;
            } else {
                rc.next = node;
                //更新rc
                rc = rc.next;
            }
        }
        if (l1 != null) {
            rc.next = l1;
        } else if (l2 != null) {
            rc.next = l2;
        }
        return result;
    }


}
